package com.lingx.service.query;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lingx.model.IContext;
import com.lingx.model.IPerformer;
import com.lingx.utils.SQLUtils;
import com.lingx.utils.Utils;

@Component
public class SearchCondition implements IGridCondition{


	public static final String formatString(String temp,String key,String value){
		temp=temp.replaceAll("\\$\\{"+key+"\\}", value);
		return temp;
	}

	@Override
	public String getCondition(Map<String, Object> params, IContext context, IPerformer performer) {
		String temp="";
		if(Utils.isNotNull(context.getEntity().getConfigs().getList().get(0).getQueryField())) {
			String json=context.getEntity().getConfigs().getList().get(0).getQueryField();
			if(json.charAt(0)=='[') {
				List<Map<String,Object>> list=(List<Map<String,Object>>)JSON.parse(json);
				StringBuilder sb=new StringBuilder();
				for(Map<String,Object> map:list) {
					String fieldcode=map.get("field").toString();
					if(params.containsKey(fieldcode)&&!"".equals(params.get(fieldcode).toString())) {
						temp=SQLUtils.getValue(params.get(fieldcode));//SQL注入检测
						if(Utils.isNull(temp))continue;//值为空，不处理
						sb.append(formatString(map.get("where").toString(),fieldcode,temp));
					}
				}
				temp=sb.toString();
			}
		}
		return temp;
	}

	
}
